package cmd

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/cobra"
)

var mysqlHost, mysqlUser, mysqlPwd string

// mysql实例通过ping 存活检查
var pingMysqlCheck = &cobra.Command{
	Use:   "mysqlping",
	Short: "这是mysql ping alive 检查工具",
	Args:  cobra.ArbitraryArgs, //接收任意参数
	Run: func(cmd *cobra.Command, args []string) {
		CheckMysqlAlive(mysqlUser, mysqlPwd, mysqlHost, mysqlPort)
	},
}

func CheckMysqlAlive(mysqluser, mysqlpwd, mysqlhost string, mysqlport int) {

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s",
		mysqlUser, mysqlPwd, mysqlHost, mysqlPort, "mysql")
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("failed to open database connection: %v", err)
	}

	if err = db.Ping(); err != nil {
		fmt.Printf("mysqlping,host=%s,port=%d status=%di\n", mysqlHost, mysqlPort, status)
	} else {
		status := 1
		fmt.Printf("mysqlping,host=%s,port=%d status=%di\n", mysqlHost, mysqlPort, status)
	}

}

func init() {
	//将子命令pingMysqlCheck添加到主命令rootCmd中
	rootCmd.AddCommand(pingMysqlCheck)
	pingMysqlCheck.Flags().StringVarP(&mysqlUser, "user", "u", "monitor", "数据库用户")
	pingMysqlCheck.Flags().StringVarP(&mysqlPwd, "pwd", "p", "monitor", "数据库密码")
	pingMysqlCheck.Flags().StringVarP(&mysqlHost, "host", "H", "127.0.0.1", "数据库IP")
	pingMysqlCheck.Flags().IntVarP(&mysqlPort, "port", "P", 3306, "数据库端口")
}
